package com.flow.plugins;

import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.exception.BusinessException;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.tools.DataMap;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import oracle.jdbc.driver.DatabaseError;
import org.apache.log4j.Logger;
import org.owasp.esapi.ValidationErrorList;

import javax.xml.crypto.Data;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提交审核时，初始化审核表audit。
 */
@SuppressWarnings("serial")
public class FlowInitPluginImpl implements CustomMethodPlugin {

    protected Logger log = Logger.getLogger(getClass());

    public Object doInvoke(Map<String, Object> param) {

        //1. ifStart=T and auditType=参数
        //list

        //2.通过遍历每个节点获取其nodeConfig，进行解析找到next节点编号

        //3.根据next节点编号获取当前节点，判断当前节点的nodeType是否为task节点，如果是task节点，存到审核表中，如果是judge节点，重复第二步



        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 初始化审核表
     * params：
     */
    public Object beforeInvoke(Map<String, Object> param) {
        String auditType = String.valueOf(param.get("auditType"));
        String proId = String.valueOf(param.get("id"));
        String proName = String.valueOf(param.get("name"));

        ResultEntity reslutEntity = new ResultEntity();
        if (Validator.isNull(proId)) {
            proId = Validator.generate();
        }
        if (Validator.isNull(auditType)) {
            throw new BusinessException("提交审核时auditType参数不能为空！");
        }
        log.info("【启动审核任务】 - > auditType="+auditType+",proId="+proId);
        String ifStart = "T";

        //找到开始节点（有可能出现多个）
        String searchObjName = "s_sysAuditRule";
        Map<String, Object> whereMap = new HashMap<String, Object>();
        whereMap.put("sysAuditRule.w_auditType", auditType);
        whereMap.put("sysAuditRule.w_ifStart", ifStart);
        whereMap.put("sysAuditRule.w_nodeType", "start");
        ResultEntity dymicSqlParamResult = (ResultEntity) IusPluginUtil.getInstance().select("plateform","list",searchObjName,whereMap);
        List<DataMap> firstNodeList = (List<DataMap>) dymicSqlParamResult.getEntity();
        String nextNodeCode="";
        for (DataMap node:firstNodeList) {
            String nodeType="";
            nodeType = String.valueOf(node.get("nodeType"));
            String nodeConfig = String.valueOf(node.get("nodeConfig"));
            JSONObject jObject = JSONObject.fromObject(nodeConfig);
            JSONArray jsonArray = (JSONArray)jObject.get("nexts");

            if(jsonArray.size()>0){
                for(int i=0;i<jsonArray.size();i++){
                    JSONObject job = jsonArray.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                    nextNodeCode = String.valueOf(job.get("code"));
                    DataMap nextTaskNodeInfo = getNodeByCode(param,nextNodeCode);

                    if(nextTaskNodeInfo!=null){
//                        System.out.println("======================="+nextTaskNodeInfo.get("taskName"));
                        if(!"end".equals(nextTaskNodeInfo.get("nodeType"))){
                            nextTaskNodeInfo.put("pro_id",proId);
                            nextTaskNodeInfo.put("pro_name",proName);
                            reslutEntity = initAudit(nextTaskNodeInfo);
                        }else{
                            log.info("【已到结束节点】流程结束！！");
                        }
                    }

                }
            }

        }





//
//        String objName = String.valueOf(firstTaskMap.get("tableName"));
//        String colName = String.valueOf(firstTaskMap.get("colName"));
//
//        if (Validator.isNotNull(objName) && Validator.isNotNull(colName)) {
//            param.put(objName + "." + colName, proId);
//            return param;
//        }

        Map<String, Object> result = new HashMap<String, Object>();
        result.put(CustomMethodPlugin.resultMark, "操作成功");
        result.put(CustomMethodPlugin.pluginInnerReturn, reslutEntity.getEntity());
        return result;

    }

    public Object afterInvoke(Map<String, Object> param) {

        return null;
    }


    private ResultEntity initAudit(DataMap taskMap){
            String saveObjName = "i_sysAudit";
            Map<String, Object> paramsMap = new HashMap<String, Object>();
            paramsMap.put("sysAudit.auditType",taskMap.get("auditType"));
            paramsMap.put("sysAudit.proId",taskMap.get("proId"));
            paramsMap.put("sysAudit.auditsStatus", "10");
            paramsMap.put("sysAudit.checkUser", taskMap.get("checkUser"));
            paramsMap.put("sysAudit.nextUser", taskMap.get("next"));
            paramsMap.put("sysAudit.lastUser", taskMap.get("last"));
            paramsMap.put("sysAudit.toUrl", taskMap.get("toUrl"));
            paramsMap.put("sysAudit.createTime", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
            paramsMap.put("sysAudit.num", taskMap.get("num"));
            paramsMap.put("sysAudit.colNameY", taskMap.get("colNameY"));
            paramsMap.put("sysAudit.colNameN", taskMap.get("colNameN"));
            paramsMap.put("sysAudit.linkUrl", taskMap.get("linkUrl"));
            paramsMap.put("sysAudit.ifCustom", taskMap.get("ifCustom"));
            paramsMap.put("sysAudit.sysName", taskMap.get("sysName"));
            paramsMap.put("sysAudit.pageName", taskMap.get("pageName"));
            paramsMap.put("sysAudit.formName", taskMap.get("formName"));


            paramsMap.put("sysAudit.proName", taskMap.get("proName"));
            paramsMap.put("sysAudit.taskName", taskMap.get("taskName"));
            paramsMap.put("sysAudit.taskNo", taskMap.get("taskNo"));
            paramsMap.put("sysAudit.colName", taskMap.get("colName"));
            paramsMap.put("sysAudit.tableName", taskMap.get("tableName"));

            ResultEntity result = IusPluginUtil.getInstance().saveInvoke("plateform",saveObjName,paramsMap);
//            log.info("【初始化第一级审核任务结果】 - > taskName="+taskName+",proName="+name+",result="+ JSONObject.fromObject(result));

            if (!result.getResult().equals("T")) {
                throw new BusinessException("执行失败！");
            }
            return result;

    }

    private DataMap getNodeByCode(Map<String, Object> param,String nodeCode) {
        if(StrUtil.isNull(nodeCode)){
            return  null;
        }
        Map<String, Object> whereMap_next = new HashMap<String, Object>();
        whereMap_next.put("sysAuditRule.w_taskNo", nodeCode);
        ResultEntity nextCodeResult = (ResultEntity) IusPluginUtil.getInstance().select("plateform", "obj", "s_sysAuditRule", whereMap_next);
        DataMap nextNodeInfo = (DataMap) nextCodeResult.getEntity();
        String next_nodeType = String.valueOf(nextNodeInfo.get("nodeType"));
        if ("judge".equals(next_nodeType)) {
            //递归
            String nextNode = "";
            String nodeConfig = String.valueOf(nextNodeInfo.get("nodeConfig"));
            JSONObject jObject = JSONObject.fromObject(nodeConfig);
            JSONArray jsonArray = (JSONArray) jObject.get("nexts");
            if (jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject job = jsonArray.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                    nodeCode = String.valueOf(job.get("code"));
                    String rule = String.valueOf(job.get("rule"));
                    if(Validator.isNotNull(rule)){
                        String arg1 = rule.split("==")[0];
                        String arg2 = rule.split("==")[1];
                        if (arg2.equals(param.get(arg1))) {
                            nextNode = String.valueOf(job.get("code"));
                            break;
                        }
                    }
                }
            }
            return getNodeByCode(param, nextNode);
        }
    return nextNodeInfo;
    }
    /**
     * 规则校验入口（专门给系统公式规则提供的）
     *
     * @param paramsVo
     */
    public void run(ParamsVo paramsVo) {
        beforeInvoke(paramsVo.getParams());
    }

}
